package share

import (
	"bytes"
	"jslog/service"
	"net/http"
	"path"
	"time"

	commSer "jslog/common/service"

	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
)

type Captcha struct {
	service.Comon
}

func (s Captcha) GraphiCaptcha(c *gin.Context) {

	graphiCaptcha := new(commSer.GraphiCaptcha)
	s.Succee(graphiCaptcha.Create(c), c)
}

func (s Captcha) Show(c *gin.Context) {

	_, file := path.Split(c.Request.URL.Path)

	ext := path.Ext(file)
	id := file[:len(file)-len(ext)]
	var content bytes.Buffer

	c.Writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	c.Writer.Header().Set("Pragma", "no-cache")
	c.Writer.Header().Set("Expires", "0")
	c.Writer.Header().Set("Content-Type", "image/"+ext)

	captcha.WriteImage(&content, id, captcha.StdWidth, captcha.StdHeight)
	http.ServeContent(c.Writer, c.Request, id+"."+ext, time.Time{}, bytes.NewReader(content.Bytes()))
}

func (s Captcha) VerifyGraphiCaptcha(c *gin.Context) {

	captcha_id := c.DefaultPostForm("captcha_id", "")
	captcha := c.DefaultPostForm("captcha", "")
	if captcha_id == "" || captcha == "" {
		s.Error(500, nil, "信息不全", c)
	}

	graphiCaptcha := new(commSer.GraphiCaptcha)
	reVerify := graphiCaptcha.Verify(captcha_id, captcha, c)
	s.Succee(reVerify, c)
}
